from flask import Blueprint, request, jsonify, render_template, redirect, url_for
from flask_login import login_user, logout_user, login_required, current_user
from app import db
from app.models.user import User

bp = Blueprint('auth', __name__, url_prefix='/auth')

@bp.route('/login', methods=['GET', 'POST'])
def login():
    if request.method == 'GET':
        return render_template('login.html')

    data = request.get_json() if request.is_json else request.form
    username = data.get('username')
    password = data.get('password')

    if not username or not password:
        return jsonify({'error': 'Username and password required'}), 400

    user = User.query.filter_by(username=username).first()

    if user and user.check_password(password):
        login_user(user)
        return jsonify({
            'message': 'Login successful',
            'user': user.to_dict(),
            'redirect': url_for('auth.dashboard')
        }), 200

    return jsonify({'error': 'Invalid credentials'}), 401

@bp.route('/logout', methods=['POST'])
@login_required
def logout():
    logout_user()
    return jsonify({'message': 'Logged out successfully'}), 200

@bp.route('/register', methods=['POST'])
def register():
    data = request.get_json()

    required_fields = ['username', 'password', 'email', 'full_name']
    if not all(field in data for field in required_fields):
        return jsonify({'error': 'Missing required fields'}), 400

    if User.query.filter_by(username=data['username']).first():
        return jsonify({'error': 'Username already exists'}), 409

    if User.query.filter_by(email=data['email']).first():
        return jsonify({'error': 'Email already exists'}), 409

    user = User(
        username=data['username'],
        email=data['email'],
        full_name=data['full_name'],
        role=data.get('role', 'employee'),
        department=data.get('department'),
        manager_id=data.get('manager_id')
    )
    user.set_password(data['password'])

    db.session.add(user)
    db.session.commit()

    return jsonify({
        'message': 'User registered successfully',
        'user': user.to_dict()
    }), 201

@bp.route('/me')
@login_required
def get_current_user():
    return jsonify(current_user.to_dict()), 200

@bp.route('/dashboard')
@login_required
def dashboard():
    """根据用户角色重定向到对应的仪表板"""
    if current_user.is_admin():
        return render_template('admin_dashboard.html')
    elif current_user.is_manager():
        return render_template('manager_dashboard.html')
    else:
        return render_template('employee_dashboard.html')

@bp.route('/user/<int:user_id>')
@login_required
def user_detail(user_id):
    """查看用户详情页面"""
    user = User.query.get_or_404(user_id)

    # 权限检查：只有管理员、主管或用户本人可以查看
    if not current_user.is_manager() and current_user.id != user_id:
        return jsonify({'error': 'Access denied'}), 403

    return render_template('user_detail.html', user=user)